package com.changgou.search.controller;

import com.changgou.entity.Page;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Set;

@Controller
@RequestMapping("/search")
public class SearchController {
    @Autowired
    private SearchService searchService;

    @GetMapping("/list")
    public String list(@RequestParam Map<String,String> searchMap, Model model){
        //获取数据
        this.handleSearchMap(searchMap);
        Map result = searchService.search(searchMap);
        //model添加数据
        model.addAttribute("result",result);
        //用户请求参数返回
        model.addAttribute("searchMap",searchMap);
        //分页对象
        // 封装分页数据，并返回
        //总记录数
        // 当前页
        // 每页几条
        Page<SkuInfo> page = new Page<>(
                Long.parseLong(String.valueOf(result.get("total"))),
                Integer.parseInt(String.valueOf(result.get("pageNum"))),
                Page.pageSize
        );

        model.addAttribute("page", page);
        //保存url
        StringBuilder sb = new StringBuilder("/search/list");
        if (searchMap!=null && searchMap.size()>0) {
            sb.append("?");
            for (String key : searchMap.keySet()) {
                if (!"sortRule".equals(key)&&!"sortField".equals(key)&&!"pageNum".equals(key)){
                    sb.append(key).append("=").append(searchMap.get(key)).append("&");
                }
            }
            String urlString = sb.toString();
            urlString = urlString.substring(0, urlString.length() - 1);
            model.addAttribute("url",urlString);
        }else {
            model.addAttribute("url", sb);
        }

        return "search";
    }
    /**
     * //按照查询条件进行数据查询
     * @param searchMap
     * @return
     */
    @GetMapping
    @ResponseBody
    public Map search(@RequestParam Map<String,String> searchMap){
        //特殊符号处理 + 换成编码
        this.handleSearchMap(searchMap);
        Map map = searchService.search(searchMap);
        return map;
    }

    private void handleSearchMap(Map<String, String> searchMap) {
        Set<Map.Entry<String, String>> entries = searchMap.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            if (entry.getKey().startsWith("spec_")){
                //如果键以spec_开头把其对=号后面的值有加号的替换掉 在设置回map里
                searchMap.put(entry.getKey(),entry.getValue().replace("+","%2B"));
            }
        }
    }
}
